/**=========================================================
 * 登录登出
 =========================================================*/
'use strict';
app.factory('UserManager', function(TKHelpers,$http, $state, $q, $window, TK_CONSTANT) {
                var g_data = {
                    baseInfo: null,
                    authConfig: null
                };

                var logoutFunc = function () {
                    $http
                        .post(TKHelpers.urlPath('user/logout.json'))
                        .then(function () {
                            $window.localStorage.removeItem(TK_CONSTANT.kName);
                            $window.localStorage.removeItem(TK_CONSTANT.kPsw);
                            $window.localStorage.removeItem(TK_CONSTANT.kRememberMe);
                            g_data.baseInfo = null;
                            g_data.authConfig = null;
                            $state.go('app.home');
                        }, function () {
                            console.log('退出登录失败');
                        });
                };

                var loginFunc = function (name, psw, remember) {
                    var deferred = $q.defer();
                    $http
                        .post(TKHelpers.urlPath('user/mobile/loginToken.json'), $.param({'mobile': name}))
                        .then(
                            function (response) {
                                if (response.data.code == 'success') {
                                    var token = response.data.loginToken;
                                    var md5First = md5(psw);
                                    var md5Second = md5(md5First + token);
                                    return $http.post(TKHelpers.urlPath('user/mobile/login.json'),
                                        $.param({
                                            mobile: name,
                                            password: md5Second,
                                            rememberMe: remember
                                        }));
                                } else {
                                    deferred.reject(response.data.msg || '获取token失败');
                                }
                            },
                            function () {
                                deferred.reject('获取token失败');
                            }
                        )
                        .then(
                            function (response) {
                                if (response.data.code == 'success') {
                                    g_data.baseInfo = response.data.data;
                                    deferred.resolve(response);
                                } else {
                                    deferred.reject(response.data.msg || '登录失败');
                                }
                            },
                            function () {
                                deferred.reject('登录失败，请检查网络问题');
                            });
                    return deferred.promise;
                };

                var getUserInfo = function () {
                    return g_data.baseInfo;
                };

                var getAuthConfig = function () {
                    return g_data.authConfig || {};
                };


                var userPromise = ['$http', '$q', 'TKHelpers', function ($http, $q, TKHelpers) {
                    var deferred = $q.defer();

                    $http.post(TKHelpers.urlPath('user/getUserInfo.json'))
                        .success(function (data) {
                            if (data.code == 'success') {
                                g_data.baseInfo = data.data;
                                //登录成功后获取认证状态
                                authState().then(function() {
                                    deferred.resolve(data.data);
                                }, function() {
                                    deferred.resolve(data.data);
                                })
                            } else {
                                deferred.reject();
                            }
                        })
                        .error(function () {
                            deferred.reject();
                        });
                    return deferred.promise;
                }];


                // 进入个人中心界面需要判断登录状态
                var checkState = function (gotoState) {
                    var name = gotoState.name || '';
                    if (name.indexOf('app.user-center') >= 0 && g_data.baseInfo == null) {
                        console.log('请先登录');
                        return false;
                    }

                    return true;
                };

                // 认证情况
                function authState() {
                    return $http.post(TKHelpers.urlPath('realAuth/getStatus.json'))
                        .success(function (data) {
                            if (data.code == 'success') {
                                g_data.authConfig = data;
                            } else {
                                g_data.authConfig = null;
                            }
                        })
                }

                return {
                    login: loginFunc,
                    logout: logoutFunc,
                    getUserInfo: getUserInfo,
                    getAuthConfig: getAuthConfig,
                    userPromise: userPromise,
                    checkState: checkState
                };
            })

